package com.chanta.client.widgets;

import com.chanta.client.services.UserRegistrationService;
import com.chanta.client.services.UserRegistrationServiceAsync;
import com.chanta.shared.ChantaException;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * TODO Please comment this class..
 * 
 * @author Hakan Özdemir - Vendoo Inc.
 * @date 06.11.2013
 * 
 */
public class UserSignUp extends Composite implements HasText {

	private static UserSignUpUiBinder uiBinder = GWT.create(UserSignUpUiBinder.class);

	private final UserRegistrationServiceAsync userRegService = GWT
			.create(UserRegistrationService.class);

	interface UserSignUpUiBinder extends UiBinder<Widget, UserSignUp> {
	}

	public UserSignUp() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiField
	Button signupButton;

	@UiField
	TextBox email;

	@UiField
	PasswordTextBox password;

	public UserSignUp(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));

		// Can access @UiField after calling createAndBindUi
		signupButton.setText(firstName);
	}

	@UiHandler("signupButton")
	void onClick(ClickEvent e) {
		signupButton.setEnabled(false);
		userRegService.createUser(email.getText(), password.getText(),
				new AsyncCallback<Boolean>() {
					@Override
					public void onFailure(Throwable caught) {
						if (caught instanceof ChantaException) {
							Window.alert("Fehler " + ((ChantaException) caught).getCustomMessage());
						} else {
							Window.alert("Unbekannter Fehler");
						}
						signupButton.setEnabled(true);
					}

					@Override
					public void onSuccess(Boolean result) {
						if (Boolean.TRUE.equals(result)) {
							Window.alert("Erfolgreich angelegt. Result " + result);
						} else {
							Window.alert("Fehler. Result " + result);
						}
						signupButton.setEnabled(true);
					}
				});
	}

	public void setText(String text) {
		signupButton.setText(text);
	}

	/**
	 * Gets invoked when the default constructor is called
	 * and a string is provided in the ui.xml file.
	 */
	public String getText() {
		return signupButton.getText();
	}

}
